<script setup lang="ts">
import MenuList from "@/components/menu/MenuList.vue";
import type {menu} from "@/components/menu/MenuList.vue";
import {RouterView} from "vue-router";
import {onBeforeMount, ref} from "vue";
import type {Ref} from "vue";
import router from "@/router";
import {useCounterStore} from "@/stores/counter";
import {userLogout} from "@/api/user";

const menus: Ref<menu[]> = ref([])
menus.value = [
  {id: "1", menuName: "首页", path: "/dashboard"},
  {id: "2", menuName: "客户端", path: "/client"},
  {id: "3", menuName: "订阅管理", path: "/subscribe"},
  {id: "4", menuName: "保留消息", path: "/retain"},
  {id: "5", menuName: "用户管理", path: "/user"},
  {id: "6", menuName: "授权管理", path: "/acl"}
]

const username: Ref<string> = ref("")
onBeforeMount(() => {
  const username1 = useCounterStore().getUsername();
  if (username1) {
    username.value = username1
  }
})

const color = (name: string) => {
  let num = "";
  for (let i = 0; i < name.length; i++) {
    num += name[i].charCodeAt(0).toString();
  }
  const r = Math.min(100 + (parseInt(num.slice(0, 2), 10) % 55), 255);
  const g = Math.min(100 + (parseInt(num.slice(2, 4), 10) % 55), 255);
  const b = Math.min(100 + (parseInt(num.slice(4, 6), 10) % 55), 255);
  return `rgb(${r}, ${g}, ${b})`;
}

function logout(): void {
  userLogout().then(() => {
    useCounterStore().removeToken()
    useCounterStore().removeUsername()
    router.push({
      path: '/login'
    })
  })
}
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px">
        <el-menu default-active="1" class="el-menu-vertical-demo" background-color="#304156" text-color="#bfcbd9"
                 active-text-color="#409EFF" router>
          <MenuList :menus="menus"/>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header>
          <el-row :justify="'end'">
            <el-col :span="1">
              <el-dropdown @command="logout" trigger="click">
                <el-avatar :style="{backgroundColor: color(`${username}`)}">{{ username[0] }}</el-avatar>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-col>
          </el-row>
        </el-header>
        <el-main>
          <RouterView/>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped>
.common-layout {
  height: 100%;

  .el-container {
    height: 100%;

    .el-menu {
      height: 100%;
    }

    .el-header {
      box-shadow: 0 1px 4px rgba(0, 21, 41, 0.1);

      .el-avatar {
        margin-top: 10px
      }

      .el-avatar:hover {
        cursor: pointer
      }
    }
  }
}
</style>